// 配置路由
import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";

import ShopCart from "@/views/ShopCart";
import Trade from "@/views/Trade";
import Pay from "@/views/Pay";
import Center from "@/views/Center";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path:'/home',
    component: ()=>import('@/views/Home/index.vue'),
    meta: { 
      show: true
     }
  },
  {
    path:'/login',
    component: ()=>import('@/views/Login/index.vue'),
    meta: { 
      show: false
     }
  },
  {
    path:'/search/:keyword?',
    component: ()=>import('@/views/Search/index.vue'),
    meta: { 
      show: true
     },
     name:'search'
  },
  {
    path:'/register',
    component: ()=>import('@/views/Register/index.vue'),
    meta: { 
      show: false
     }
  },
  {
    path:'/detail/:skuid',
    component: ()=>import('@/views/Detail/index.vue'),
    meta: { 
      show: true
     }
  },
  {
    path:'/addcartsuccess',
    name: 'addcartsuccess',
    component: ()=>import('@/views/AddCartSuccess/index.vue'),
    meta: { 
      show: true
     }
  },
  {
    path:'/ShopCart',
    component: ShopCart,
    meta: {
      show: true
    }
  },
  {
    path:'/trade',
    component: Trade,
    meta: {
      show: true
    }
  },
  {
    path:'/pay',
    component: Pay,
    meta: {
      show: true
    },
    beforeEnter: (to,from,next) => {
      if (from.path === '/trade') {
        next()
      } else {
        next(from.path)
      }
    }
  },
  {
    path:'/center',
    component: Center,
    children: [
      {
        path: '',
        redirect: 'myOrder'
      },
      {
        path: 'myOrder',
        component: ()=>import('@/views/Center/myOrder')
      },
      {
        path: 'groupOrder',
        component: ()=>import('@/views/Center/groupOrder')
      }
    ],
    meta: {
      show: true
    }
  }
]

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
    return originalPush.call(this, location).catch(err => err);
};

const router = new VueRouter({
  routes,
  scrollBehavior (){
    // 返回的y等于0代表滚动条在最上方
    return {y:0}
  }
})

// 全局前置守卫
router.beforeEach((to,from,next)=>{
  let token = store.state.register.token
  let info = store.state.register.info.id
  let list = ['/login', '/register', '/home', '/404']
  let toPath = to.path
  if (token && info) {
    if (toPath === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    if (list.includes(toPath)) {
      next()
    } else {
      next('/login?redirct=' + toPath)
    }
  }
})

export default router